package com.hruiworks.campusgroup.sse;

import com.alibaba.fastjson2.JSON;
import com.hruiworks.campusgroup.common.SseBaseResponse;
import com.hruiworks.campusgroup.enums.SuccessCode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.hruiworks.campusgroup.enums.SseMessageType.HEARTBEAT;

@Data
@Slf4j
// 自定义Emitter包装类
public class ManagedEmitter {

    private final SseEmitter emitter;

    private final ScheduledFuture<?> heartbeatTask;

    private final String heartbeat = JSON.toJSONString(new SseBaseResponse<>(null, SuccessCode.COMMON_SUCCESS, HEARTBEAT.getMessageType()));

    // 存活情况
    private final AtomicBoolean isCancelled = new AtomicBoolean(false);


    public ManagedEmitter(SseEmitter emitter, ScheduledExecutorService scheduler) {
        this.emitter = emitter;
        this.heartbeatTask = scheduler.scheduleAtFixedRate(
                this::sendHeartbeat, 0, 30, TimeUnit.SECONDS);
    }

    private void sendHeartbeat() {
        try {
            emitter.send(heartbeat);
//            System.out.println(emitter + "-心跳成功");
//            log.info("发送心跳成功");
        } catch (IOException e) {
//            e.printStackTrace();
            heartbeatInterrupt("心跳失败");
        }

    }

    public void heartbeatInterrupt(String message) {
        // 确保只取消一次
        if (isCancelled.compareAndSet(false, true)) {
            // 停止定时任务（true 表示中断正在执行的任务）
            boolean cancel = heartbeatTask.cancel(true);
//            emitter.complete();
        }
    }

}